package com.dt.web.excel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.dt.system.domain.ModRepositories;
import com.dt.system.domain.ModRepositoriesBox;
import com.dt.system.service.IModRepositoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * 直接用map接收数据
 *
 * @author yxg
 */
@Component
public class RepositoriesDataListener extends AnalysisEventListener<Map<Integer, String>> {


    private static IModRepositoriesService repositoriesService;  //库房服务


    @Autowired
    public void setService(IModRepositoriesService repositoriesService){
        RepositoriesDataListener.repositoriesService=repositoriesService;
     }


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        System.out.println("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {

        List<ModRepositories> dataList=new ArrayList<>();
        //遍历所有行数
        for (Map<Integer,String> item: cachedDataList) {
            //创建对象
            ModRepositories modRepositories=new ModRepositories();
            modRepositories.setName(item.get(1));
            modRepositories.setRepositoriesNo(item.get(2));
            modRepositories.setShelvesNum(Integer.parseInt(item.get(3)));
            modRepositories.setLayerNum(Integer.parseInt(item.get(4)));
            modRepositories.setBoxNum(Integer.parseInt(item.get(5)));
            modRepositories.setFileUseNum(Long.parseLong(item.get(6)));
            modRepositories.setAddress(item.get(7));

            //查询数据是否存在，如果不存在，则新增，存在则忽略
            ModRepositories temp=new ModRepositories();
            temp.setRepositoriesNo(item.get(2));
            List<ModRepositories> lst = repositoriesService.selectModRepositoriesList(temp);
            if(lst==null || lst.isEmpty())
            {
                //写入数据库
               dataList.add(modRepositories);
            }
        }


        if(!dataList.isEmpty()){
            repositoriesService.batchInsertModRepositories(dataList);
        }


    }
}